package com.zq.vaccinum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zq.vaccinum.domain.LoginUser;
import com.zq.vaccinum.domain.entity.User;
import com.zq.vaccinum.mapper.PermissionsMapper;
import com.zq.vaccinum.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户信息查询服务
 * @Author: zq
 * @Date: 2023/08/06/12:51
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionsMapper permissionsMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        // 查询用户信息
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        // 查询用户的权限信息
        Set<String> permissionSet = permissionsMapper.selectPermissionByUserId(user.getId());
        String redisTokenKey = UUID.randomUUID().toString();
        // 吧数据封装成UserDetails(LoginUser)返回
        LoginUser loginUser = new LoginUser();
        loginUser.setPermissions(permissionSet);
        loginUser.setUser(user);
        loginUser.setToken(redisTokenKey);
        return loginUser;
    }
}
